<?php

namespace App\Admin\Http\Controllers\Rbac;

use DB;
use Flash;
use Exception;
use Illuminate\Http\Request;
use App\Admin\Eloquent\Permission;
use App\Admin\Http\Controllers\Controller;
use App\Extensions\Pagination\BootstrapThreePresenter;

class PermissionsController extends Controller
{
    /**
     * 权限列表信息
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $query = $request->only('search');

        $permissions = Permission::paginateQuery($query);

        $permissions->load('parent');

        // 追加分页查询条件
        if (!empty($query)) {
            $permissions->appends($query);
        }

        // 分页查询代码
        $links = (new BootstrapThreePresenter($permissions))->render();

        return view('admin.rbac.permissions.index', compact('permissions', 'links', 'query'));
    }

    /**
     * 权限详细信息
     *
     * @param  mixed  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $permission = $this->permission($id);

        return view('admin.rbac.permissions.show', compact('permission'));
    }

    /**
     * 新增权限表单
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $parents = $this->getPermissionParents(Permission::get());

        return view('admin.rbac.permissions.create', compact('parents'));
    }

    /**
     * 新增权限信息
     *
     * @param  Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $permission = new Permission($request->input());

        if (!$permission->save()) {
            return back()
                ->withErrors($permission->getErrors())
                ->withInput();
        }

        Flash::success('新增权限信息成功');

        return $this->redirectAction('Rbac\PermissionsController@show', [ $permission ]);
    }

    /**
     * 编辑权限表单
     *
     * @param  mixed  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $permission = $this->permission($id);

        $parents = $this->getPermissionParents(Permission::get());

        return view('admin.rbac.permissions.edit', compact('permission', 'parents'));
    }

    /**
     * 修改角色信息
     *
     * @param  mixed  $id
     * @param  Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update($id, Request $request)
    {
        $permission = $this->permission($id);

        if (!$permission->update($request->input())) {
            return back()
                ->withErrors($permission->getErrors())
                ->withInput();
        }

        Flash::success('修改权限信息成功');

        return $this->redirectAction('Rbac\PermissionsController@show', [$permission]);
    }

    /**
     * 删除权限信息
     *
     * @param  mixed  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $permission = $this->permission($id);

        DB::beginTransaction();
        try {
            $permission->delete();
        } catch (Exception $e) {
            DB::rollBack();

            Flash::error("删除失败，{$e->getMessage()}。");

            return $this->redirectAction('Rbac\PermissionsController@index');
        }
        DB::commit();

        Flash::success('删除权限信息成功');

        return $this->redirectAction('Rbac\PermissionsController@index');
    }

    /**
     * 通过权限 id 查找权限
     *
     * @param  mixed  $id
     * @return \App\Role
     */
    protected function permission($id)
    {
        $permission = Permission::findOrFail($id);

        return $permission;
    }

    /**
     * 获取父级权限
     *
     * @param  \Illuminate\Support\Collection $permissions
     * @param  int $pid
     * @param  int $level
     * @return Permission[]
     */
    protected function getPermissionParents($permissions, $pid = 0, $level = 0)
    {
        $collection = collect();

        foreach ($permissions->where('pid', $pid) as $permission) {
            $permission->level = $level;

            $collection->push($permission);

            $collection = $collection->merge($this->getPermissionParents($permissions, $permission->id, $level + 1));
        }

        return $collection;
    }
}